<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <div class="search-wrapper">
      <el-form ref="queryFormRef" :model="deviceQueryForm" :inline="true">
        <el-form-item :label="$t('device.associatedStation')" prop="stationId">
          <el-select
              v-model="deviceQueryForm.stationId"
              :placeholder="
              $t('common.placeholderSelect') + $t('device.associatedStation')
            "
              clearable
          >
            <el-option
                v-for="(item, index) in associatedStationList"
                :key="index"
                :label="locale ? item.stationCnName : item.stationEnName"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('device.deviceName')" prop="id">
          <el-select
              v-model="deviceQueryForm.id"
              :placeholder="
              $t('common.placeholderSelect') + $t('device.deviceName')
            "
              clearable
          >
            <el-option
                v-for="(item, index) in deviceList"
                :key="index"
                :label="locale ? item.deviceCnName : item.deviceEnName"
                :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button @click="search" type="primary" icon="Search">{{
              $t("common.search")
            }}</el-button>
          <el-button @click="adddevice" type="primary" icon="Plus">{{
              $t("common.add")
            }}</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 2. 引入通用表单对话框组件 -->
    <CommonFormDialog
        :dialog-title="dialogTitle"
        v-model="dialogVisible"
        :dialog-width="dialogWidth"
        :form-data="deviceForm"
        :form-rules="deviceRules"
        :submit-loading="submitLoading"
        @close="close"
        @cancel="cancel"
        @submit="handleFormSubmit"
        @before-close="handleDialogBeforeClose"
        ref="dialogRef"
    >
      <!-- 2.1 自定义表单项（插槽：标签的“名称”和“排序”） -->
      <template #formItems>
        <el-form-item :label="$t('device.associatedStation')" prop="stationId">
          <el-select
              v-model="deviceForm.stationId"
              :placeholder="
              $t('common.placeholderSelect') + $t('device.associatedStation')
            "
              clearable
          >
            <el-option
                v-for="(item, index) in associatedStationList"
                :key="index"
                :label="locale ? item.stationCnName : item.stationEnName"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('device.deviceCnName')" prop="deviceCnName">
          <el-input
              v-model="deviceForm.deviceCnName"
              :placeholder="
              $t('common.placeholderInput') + $t('device.deviceCnName')
            "
              clearable
              maxLength="50"
          />
        </el-form-item>
        <el-form-item :label="$t('device.deviceEnName')" prop="deviceEnName">
          <el-input
              v-model="deviceForm.deviceEnName"
              :placeholder="
              $t('common.placeholderInput') + $t('device.deviceEnName')
            "
              clearable
              maxLength="50"
          />
        </el-form-item>
        <el-form-item :label="$t('device.deviceIp')" prop="deviceIp">
          <el-input
              v-model="deviceForm.deviceIp"
              :placeholder="$t('common.placeholderInput') + $t('device.deviceIp')"
              clearable
              maxLength="50"
          />
        </el-form-item>
        <el-form-item :label="$t('device.agreementType')" prop="agreementType">
          <el-select
              v-model="deviceForm.agreementType"
              @change="agreementChange"
              :placeholder="
              $t('common.placeholderSelect') + $t('device.agreementType')
            "
              clearable
          >
            <el-option
                v-for="(item, index) in agreementTypeEnums"
                :key="index"
                :label="locale ? item.cndesc : item.endesc"
                :value="item.code"
            />
          </el-select>
        </el-form-item>
        <template v-if="deviceForm.agreementType == 1">
          <el-form-item
              :label="$t('device.mqttSourceType')"
              prop="mqttSourceType"
          >
            <el-select
                v-model="deviceForm.mqttSourceType"
                @change="mqttSourceChange"
                :placeholder="
                $t('common.placeholderSelect') + $t('device.mqttSourceType')
              "
                clearable
            >
              <el-option
                  v-for="(item, index) in mqttSourceTypeEnums"
                  :key="index"
                  :label="locale ? item.cndesc : item.endesc"
                  :value="item.code"
              />
            </el-select>
          </el-form-item>
        </template>
        <!-- 可扩展：如需其他表单项（如“颜色”“描述”），直接在这里添加 -->
      </template>
    </CommonFormDialog>

    <el-card>
      <el-row>
        <el-col :span="24">
          <el-card
          ><!-- 数据表格 -->
            <el-table
                max-height="600"
                :data="tableData"
                style="width: 100%"
                @selection-change="handleSelectionChange"
            >
              <el-table-column
                  :label="$t('common.sn')"
                  type="index"
                  width="150"
              />
              <el-table-column
                  :label="$t('device.associatedStation')"
                  align="center"
                  prop="deviceCnName"
              >
                <template #default="scope">
                  {{ getassoStationNameById(scope.row.stationId) }}
                </template>
              </el-table-column>
              <el-table-column
                  :label="$t('device.deviceCnName')"
                  align="center"
                  prop="deviceCnName"
              />
              <el-table-column
                  :label="$t('device.deviceEnName')"
                  align="center"
                  prop="deviceEnName"
              />
              <el-table-column
                  :label="$t('device.deviceIp')"
                  align="center"
                  prop="deviceIp"
              />
              <el-table-column
                  :label="$t('device.agreementType')"
                  align="center"
                  prop="agreementType"
              >
                <template #default="scope"
                >{{ getagreementTypeById(scope.row.agreementType) }}
                </template>
              </el-table-column>
              <el-table-column
                  :label="$t('device.mqttSourceType')"
                  align="center"
                  prop="mqttSourceType"
              >
                <template #default="scope">{{
                    getMqttSourceTypeById(scope.row.mqttSourceType)
                  }}</template>
              </el-table-column>
              <el-table-column
                  :label="$t('common.createTime')"
                  align="center"
                  prop="createTime"
              />
              <el-table-column
                  :label="$t('common.updateTime')"
                  align="center"
                  prop="updateTime"
              />
              <el-table-column
                  label="操作"
                  align="center"
                  width="350"
                  fixed="right"
              >
                <template #default="scope">
                  <el-tooltip :content="scope.row.deviceStatus != 1?$t('common.deviceModelDisable'):$t('common.deviceModelEnable')"  placement="top">
                    <el-button
                        :disabled="scope.row.deviceStatus != 1"
                        type="primary"
                        link
                        icon="Setting"
                        @click="routerConf(scope.row.id)"
                    >{{ $t("common.conf") }}</el-button
                    >
                  </el-tooltip>

                  <el-button
                      type="primary"
                      link
                      icon="Edit"
                      @click="updatedevice(scope.row)"
                  >{{ $t("common.edit") }}</el-button
                  >
                  <el-button
                      type="danger"
                      link
                      icon="Delete"
                      @click="handleDelete(scope.row)"
                  >{{ $t("common.delete") }}</el-button
                  >
                  <el-tooltip :content="scope.row.deviceEnable != 1?$t('common.deviceDisable'):$t('common.deviceEnable')"  placement="top">
                    <el-button
                        :disabled="scope.row.deviceEnable != 1"
                        type="default"
                        link
                        icon="View"
                        @click="handleDetail(scope.row.id)"
                    >{{ $t("common.detail") }}</el-button
                    >
                  </el-tooltip>

                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <div class="pagination-container">
              <el-pagination
                  v-model:current-page="deviceQueryForm.pageNum"
                  v-model:page-size="deviceQueryForm.pageSize"
                  :page-sizes="[10, 20, 30, 50]"
                  :total="total"
                  :background="true"
                  layout="total, sizes, prev, pager, next, jumper"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
              />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import { getstationListApi } from "@/api/ems/station/station.ts";
import {
  getdevicePageApi,
  getdeviceListApi,
  adddeviceApi,
  updatedeviceApi,
  deldeviceApi,
} from "@/api/ems/device/device.ts";
import { EmsDeviceEnum } from "@/enum/EmsDeviceEnum"
import { publishDevConfApi,subscribeDevConfApi } from "@/api/mqtt"
import { useRoute, useRouter } from "vue-router";
import { getEnumListByType } from "@/api/enums";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import { useI18n } from "vue-i18n";
import CommonFormDialog from "@/components/Modal/basicModal.vue"; // 引入通用组件
import { reactive, ref, onMounted, onUnmounted } from "vue";
const tableData = ref(); //表格数组
const locale = ref(window.localStorage.getItem("locale") == "zh-CN");
const router = useRouter();
const total = ref(0);
const dialogWidth = ref("600px");
// 1. 对话框状态
const dialogVisible = ref(false); // 对话框是否显示

const submitLoading = ref(false); // 提交按钮加载状态
const dialogRef = ref(); // 通用对话框组件引用
const { t } = useI18n();
const dialogTitle = ref(); // 对话框标题
// 2. 设备查询表单数据
const deviceQueryForm = reactive({
  pageNum: 1,
  pageSize: 10,
  id: null, // 设备Id
  stationId: null, // 场站Id
});
// 2. 设备新增表单数据
const deviceForm = reactive({
  stationId: null, // 场站Id
  deviceCnName: "", // 设备中文名称
  deviceEnName: "", // 设备英文名称
  deviceIp: "", //设备Ip
  deviceEnable: 0, //设备是否可用
  deviceStatus: 0, //设备状态
  agreementType: null, //协议类型(0:mqtt,1:研电)
  mqttSourceType: null, //mqtt源头类型(目前分李工和陆工)
});
// 3. 标签表单校验规则
const deviceRules = reactive({
  stationId: [
    {
      required: true,
      message: t("common.placeholderSelect"),
      trigger: "change",
    },
  ],
  deviceCnName: [
    { required: true, message: t("common.placeholderInput"), trigger: "blur" },
    { max: 50, message: t("device.inputRule"), trigger: "blur" },
  ],
  deviceEnName: [
    { required: true, message: t("common.placeholderInput"), trigger: "blur" },
    { max: 50, message: t("device.inputRule"), trigger: "blur" },
  ],
  deviceIp: [
    { required: true, message: t("common.placeholderInput"), trigger: "blur" },
    { max: 50, message: t("device.inputRule"), trigger: "blur" },
  ],
  agreementType: [
    {
      required: true,
      message: t("common.placeholderSelect"),
      trigger: "change",
    },
  ],
  mqttSourceType: [
    {
      required: true,
      message: t("common.placeholderSelect"),
      trigger: "change",
    },
  ],
});
//
//设  备列表
const deviceList = ref([]);
//关联设备列表
const associatedStationList = ref([]);
//设备可用列表枚举
const deviceEnableEnums = ref([]);
//设备可用列表状态枚举
const deviceStaEnums = ref([]);
//设备协议类型
const agreementTypeEnums = ref([]);
//设备mqtt来源类型
const mqttSourceTypeEnums = ref([]);

//查询设备列表
const getdeviceList = () => {
  getdeviceListApi().then((res) => {
    deviceList.value = res.data;
  });
};
//查询
const search = () => {
  getSelectPage();
};

const handleSizeChange = (val) => {
  deviceQueryForm.pageSize = val;
  getSelectPage();
};
const handleCurrentChange = (val) => {

  deviceQueryForm.pageNum = val;
  getSelectPage();
};
//发布消息
const publishDevConf = (id) => {
  publishDevConfApi({pKey:"Pkey" + id,sn:"Sn" + id,data:"sending"}).then((res) => {
    ElMessage.success(res.message);
  });
}
const subscribeDevConf = (id) => {
  subscribeDevConfApi({pKey:"Pkey" + id,sn:"Sn" + id}).then((res) => {
    ElMessage.success(res.message);
  });
}
//协议选择事件
const agreementChange = (val) => {
  if (val == 1) {
    deviceForm.deviceEnable = 0;
    deviceForm.deviceStatus = 1;
  } else {
    deviceForm.deviceEnable = 0;
    deviceForm.deviceStatus = 0;
  }
};
//mqtt选择事件
const mqttSourceChange = (val) => {
  if (val == 1) {
    deviceForm.deviceEnable = 0;
    deviceForm.deviceStatus = 1;
  } else {
    deviceForm.deviceEnable = 0;
    deviceForm.deviceStatus = 0;
  }
};
//跳转详情页
const handleDetail = (id) => {
  publishDevConf(id)
  subscribeDevConf(id)
  router.push({ path: "/ems/deviceDetail", query: { id: id } });
};
//跳转配置页
const routerConf = (id) => {
  router.push({ path: "/ems/deviceSettings", query: { id: id } });
};
const getSelectPage = () => {
  getdevicePageApi(deviceQueryForm).then((res) => {
    total.value = res.data.total;
    tableData.value = res.data.records;
  });
};
//获取关联设备列表
const getassoStationList = () => {
  getstationListApi().then((res) => {
    associatedStationList.value = res.data;
  });
};
//获取关联设备列表
const getassoStationNameById = (stationId) => {
  let val;
  if (!!stationId) {
    associatedStationList.value.forEach((ele) => {
      if (ele.id == stationId) {
        val = locale ? ele.stationCnName : stationEnName;
      }
    });
  }

  return val;
};
//根据ID获取协议类型枚举名称
const getagreementTypeById = (code) => {
  let val;
  if (code != null) {
    agreementTypeEnums.value.forEach((ele) => {
      if (ele.code == code) {
        val = locale ? ele.cndesc : endesc;
      }
    });
  }
  return val;
};
//根据ID获取Mqtt类型枚举名称
const getMqttSourceTypeById = (code) => {
  let val;
  if (code != null) {
    mqttSourceTypeEnums.value.forEach((ele) => {
      if (ele.code == code) {
        val = locale ? ele.cndesc : endesc;
      }
    });
  }
  return val;
};
//获取设备枚举列表
const getEnumListByTypeList = async (stype) => {
  let res = await getEnumListByType({ type: stype });
  if (stype == EmsDeviceEnum.DeviceEnableTypeEnum) {
    deviceEnableEnums.value = res.data;
  }
  if (stype == EmsDeviceEnum.DeviceStatusTypeEnum) {
    deviceStaEnums.value = res.data;
  }
  if (stype == EmsDeviceEnum.AgreementTypeEnum) {
    agreementTypeEnums.value = res.data;
  }
  if (stype == EmsDeviceEnum.MqttSourceTypeEnum) {
    mqttSourceTypeEnums.value = res.data;
  }
};
// 关闭对话框时，触发 update:modelValue 事件
const close = () => {
  dialogVisible.value = false; // 通知父组件将 dialogVisible 设为 false
};
// 关闭对话框时，触发 update:modelValue 事件
const cancel = () => {
  dialogVisible.value = false; // 通知父组件将 dialogVisible 设为 false
};
//新增调出弹框
const adddevice = () => {
  dialogVisible.value = true;
  Object.assign(deviceForm, {
    id:null,
    stationId: null, // 场站Id
    deviceCnName: "", // 设备中文名称
    deviceEnName: "", // 设备英文名称
    deviceIp: "", //设备Ip
    deviceEnable: null, //设备是否可用
    deviceStatus: null, //设备状态
    agreementType: null, //协议类型(0:mqtt,1:研电)
    mqttSourceType: null, //mqtt源头类型(目前分李工和陆工)
  });
  dialogTitle.value = t("device.deviceAdd");
};
//修改调出弹框
const deviceId = ref();
const updatedevice = (row) => {
  dialogTitle.value = t("device.deviceUpdate");
  dialogVisible.value = true;
  deviceId.value = row.id;
  Object.assign(deviceForm, row);
};
const handleDialogBeforeClose = () => {
  dialogVisible.value = false; // 通知父组件将 dialogVisible 设为 false
};
//提交数据
const handleFormSubmit = () => {
  if (dialogTitle.value == t("device.deviceAdd")) {
    addDeviceApi(deviceForm).then((res) => {
      if (res.code == 200) {
        ElMessage.success(t("common.success"));
        getSelectPage();
        dialogVisible.value = false;
      } else {
        ElMessage.success(t("common.success"));
      }
    });
  } else {
    updateDeviceApi(Object.assign(deviceForm)).then((res) => {
      if (res.code == 200) {
        ElMessage.success(t("common.success"));
        getSelectPage();
        dialogVisible.value = false;
      } else {
        ElMessage.success(t("common.success"));
      }
    });
  }
};
//删除数据
const handleDelete = (row) => {
  ElMessageBox.confirm(`是否确认删除`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    delDeviceApi(row.id).then((res) => {
      if (res.code == 200) {
        ElMessage.success(t("common.success"));
        getSelectPage();
      } else {
        ElMessage.success(t("common.error"));
      }
    });
  });
};

onMounted(() => {
  getSelectPage();
  getassoStationList();
  getdeviceList();
  getEnumListByTypeList("deviceEnable"); //获取设备可用
  getEnumListByTypeList("deviceStatus"); //获取设备可用
  getEnumListByTypeList("agreementType"); //获取设备可用
  getEnumListByTypeList("mqttSourceType"); //获取设备可用
});
onUnmounted(() => {});
</script>
<style lang="scss" scoped>
:root[data-theme="dark"] {
  .app-container {
    :deep(.el-dialog) {
      .el-form {
        .el-input__wrapper {
          box-shadow: 0 0 0 1px var(--el-border-color) inset;
        }
      }
    }
  }
}
.app-container {
  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }

  :deep(.el-dialog) {
    .el-dialog__body {
      padding: 20px 40px;
    }

    .el-form {
      .el-form-item {
        margin-bottom: 22px;

        &:last-child {
          margin-bottom: 0;
        }

        .el-form-item__label {
          font-weight: 500;
          padding-right: 20px;
        }
      }

      .el-select {
        width: 100%;
      }
    }
  }
}
</style>
